import { useState } from 'react'
import { useTasks, useTasksDispatch, Task } from './TasksContext'

export default function TaskList() {
  const tasks = useTasks()
  return (
    <ul>
      {tasks.map(task => (
        <li key={task.id}>
          <TaskItem task={task} />
        </li>
      ))}
    </ul>
  )
}

interface TaskContentProps {
  task: Task
  isEditing: boolean
  onEdit: () => void
  onSave: () => void
}

// 处理任务的内容展示和编辑
function TaskContent({ task, isEditing, onEdit, onSave }: TaskContentProps) {
  const dispatch = useTasksDispatch()

  if (isEditing) {
    return (
      <>
        <input
          value={task.text}
          onChange={e => {
            dispatch({
              type: 'changed',
              task: { ...task, text: e.target.value },
            })
          }}
        />
        <button onClick={onSave}>Save</button>
      </>
    )
  }

  return (
    <>
      {task.text}
      <button onClick={onEdit}>Edit</button>
    </>
  )
}

interface TaskDeleteButtonProps {
  taskId: number
}

// 处理任务的删除操作
function TaskDeleteButton({ taskId }: TaskDeleteButtonProps) {
  const dispatch = useTasksDispatch()
  return (
    <button
      onClick={() => {
        dispatch({ type: 'deleted', id: taskId })
      }}
    >
      Delete
    </button>
  )
}

interface TaskItemProps {
  task: Task
}

// 主任务组件
function TaskItem({ task }: TaskItemProps) {
  const [isEditing, setIsEditing] = useState(false)
  const dispatch = useTasksDispatch()

  return (
    <label>
      <input
        type="checkbox"
        checked={task.done}
        onChange={e => {
          dispatch({
            type: 'changed',
            task: { ...task, done: e.target.checked }
          })
        }}
      />

      <TaskContent
        task={task}
        isEditing={isEditing}
        onEdit={() => setIsEditing(true)}
        onSave={() => setIsEditing(false)}
      />

      <TaskDeleteButton taskId={task.id} />
    </label>
  )
}
